package com.atguigu.eduorder.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.eduorder.entity.Order;
import com.atguigu.eduorder.entity.PayLog;
import com.atguigu.eduorder.mapper.PayLogMapper;
import com.atguigu.eduorder.service.OrderService;
import com.atguigu.eduorder.service.PayLogService;
import com.atguigu.eduorder.utils.HttpClient;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-06-24
 */
@Service
public class PayLogServiceImpl extends ServiceImpl<PayLogMapper, PayLog> implements PayLogService {

    @Autowired
    OrderService orderService;

    @Override
    public Map<String, Object> createNative(String orderNo) {
        try {
            //1、根据订单号查询订单信息
            QueryWrapper<Order> wrapper=new QueryWrapper<>();
            wrapper.eq("order_no",orderNo);
            Order order = orderService.getOne(wrapper);
            //2、设置支付参数
            Map<String,String > m=new HashMap<>();
            m.put("appid", "wx74862e0dfcf69954");
            //商户号
            m.put("mch_id", "1558950191");
            m.put("nonce_str", WXPayUtil.generateNonceStr());
            //课程标题
            m.put("body", order.getCourseTitle());
            m.put("out_trade_no", orderNo);
            //将价格转成字符串
            m.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");
            //IP地址
            m.put("spbill_create_ip", "127.0.0.1");
            //回调地址，暂时不用
            m.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");
            m.put("trade_type", "NATIVE");
            //3、HTTPClient来根据URL访问第三方接口并且传递参数
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //httpclient设置参数
            //设置Xml格式的参数，key是商户key
            client.setXmlParam(WXPayUtil.generateSignedXml(m,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            //开发https，默认是不开启的
            client.setHttps(true);
            //发送post请求
            client.post();
            //4、获取第三方返回的数据,返回的内容是xml格式的
            String xml = client.getContent();
            //将数据转成map
            Map<String,String> result=WXPayUtil.xmlToMap(xml);
            //5、封装返回结果集
            Map<String,Object> map = new HashMap<>();
            //订单号
            map.put("out_trade_no", orderNo);
            map.put("course_id", order.getCourseId());
            //价格
            map.put("total_fee", order.getTotalFee());
            //二维码操作状态
            map.put("result_code", result.get("result_code"));
            //二维码地址
            map.put("code_url", result.get("code_url"));
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001,"二维码获取失败");
        }
    }

    @Override
    public Map<String, String> queryPayStaues(String orderNo) {
        try {
            Map<String,String> m=new HashMap<>();
            m.put("appid", "wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("out_trade_no", orderNo);
            m.put("nonce_str", WXPayUtil.generateNonceStr());
            //发送查询状态请求
            HttpClient client=new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();
            String xml = client.getContent();
            //返回查询结果
            Map<String, String> map = WXPayUtil.xmlToMap(xml);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            //如果查询出错就返回null
            return null;
        }
    }

    @Override
    public void updatePayStatus(Map<String,String> map) {
        //获取订单号
        String orderNo = map.get("out_trade_no");
        QueryWrapper<Order> wrapper=new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        Order order = orderService.getOne(wrapper);
        //已支付直接返回
        if(order.getStatus().intValue() == 1){
            return;
        }
        //更新支付状态
        order.setStatus(1);
        orderService.updateById(order);
        //向支付日志添加一条记录
        PayLog payLog=new PayLog();
        //支付订单号
        payLog.setOrderNo(order.getOrderNo());
        payLog.setPayTime(new Date());
        payLog.setPayType(1);//支付类型
        payLog.setTotalFee(order.getTotalFee());//总金额(分)
        //支付状态
        payLog.setTradeState(map.get("trade_state"));
        //交易流水号
        payLog.setTransactionId(map.get("transaction_id"));
        //其他属性
        payLog.setAttr(JSONObject.toJSONString(map));
        //保存记录
        baseMapper.insert(payLog);
    }
}
